package com.road.vast.springboot;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @Author 郭泽鹏
 * @Date 2020/7/31 14:34
 * @Version 1.0
 * @Description 模拟通过Shiro进行用户认证登录
 */
@SpringBootTest
public class ShiroTest01 {
    /**
     * 测试用户认证
     *      认证：用户登录
     *
     *      1.加载ini配置文件
     *      2.把数据源绑定到DefaultSecurityManager实例中
     *      3.把manager绑定到SecurityUtils
     *      4.从当前环境中构造subject对象
     *      5.构造shiro登录的数据
     *      6.创建令牌
     *      7.主体登录
     *      8.验证用户是否登录成功
     *      9.获取登录成功的数据
     */
    @Test
    public void testLogin(){
        //1.加载ini配置文件
        DefaultSecurityManager manager = new DefaultSecurityManager();
        IniRealm realm = new IniRealm("classpath:shiro-auth-01.ini");

        //2.把数据源绑定到DefaultSecurityManager实例中
        manager.setRealm(realm);

        //3.把manager绑定到SecurityUtils
        SecurityUtils.setSecurityManager(manager);

        //4.从当前环境中构造subject对象
        Subject subject = SecurityUtils.getSubject();

        //5.构造shiro登录的数据
        String username = "zhangsan";
        String password = "123456";

        //6.创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        //7.主体登录
        subject.login(token);

        //8.验证用户是否登录成功
        System.out.println("用户是否登录成功：" + subject.isAuthenticated());

        //9.获取登录成功的数据
        System.out.println(subject.getPrincipal());
    }
}
